#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
#define NUM 1024
#define SIZE 32
#define SEP " "
char* g_argv[SIZE];
char cmd_line[NUM] = { 0 };
char g_env[SIZE];
int main()
{
    while(1)
    {
        printf("[root@我的主机: myshell]#");
        fflush(stdout);
        //sleep(2);
        
        //memset(cmd_line，'\0', sizeof(cmd_line));
       // memset(cmd_line，'\0', sizeof cmd_line );


        if(fgets(cmd_line, sizeof(cmd_line), stdin) == NULL)
        {
            continue;
        }
        cmd_line[strlen(cmd_line) - 1] = '\0';
        //printf("echo::%s\n",cmd_line);
       g_argv[0] =  strtok(cmd_line, SEP);//第一次提取
       int index = 1;//0用过了
       if(strcmp(g_argv[0], "ls") == 0)
       {
           g_argv[index++] = "--color=auto";
       }
        if(strcmp(g_argv[0], "ll") == 0)
        {
            g_argv[0] = "ls";
            g_argv[index++] = "-l";
            g_argv[index++] = "--color=auto";
        }
        while(g_argv[index++] = strtok(NULL,SEP));
        if(strcmp(g_argv[0], "export") == 0 && g_argv[1] != NULL)
        {
            strcpy(g_env, g_argv[1]);
            putenv(g_env);
            continue;
        }

       // for(index = 0; g_argv[index]; index++)//g_argv 最后是NULL
       // {
       //     printf("g_argv[%d]=%s\n",index, g_argv[index]);
       // }
        //内建命令
        if(strcmp(g_argv[0], "cd") == 0)
        {
            if(g_argv[1] != NULL)
            {
                chdir(g_argv[1]);
            }
            continue;
        }

        pid_t id = fork();
        if(id == 0)//child
        {
            printf("下面功能是让子进程执行的\n");
            execvp(g_argv[0], g_argv);
            exit(1);
        }
        //father
        int status = 0;
        pid_t ret = waitpid(id, &status, 0);
        if(ret > 0)
        {
            printf("exit code::%d\n",WEXITSTATUS(status));
        }

    }

    return 0;
}
